/*
 * AgendaNotePanel.java
 *
 * Created on 15 mars 2008, 15:15
 */

package sheep.view;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.LinkedList;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableCellRenderer;
import org.jdesktop.animation.timing.Animator;
import org.jdesktop.animation.timing.TimingTarget;
import org.jdesktop.swingx.JXCollapsiblePane;
import org.jdesktop.swingx.JXPanel;
import org.jdesktop.swingx.JXTable;
import sheep.controller.Workspace;
import sheep.model.Worker;
import sheep.view.Component.UserTableModel;
import sheep.view.Component.ActionButton;
import sheep.view.Component.RoundedPanel;
import sheep.view.Component.SheepScrollbarUI;
import sheep.view.Component.UserCellRenderer;
import sheep.view.Component.UsersChooser;
import sheep.view.ProjectNewPanel.ManagerListModel;
import sheep.view.ProjectNewPanel.UserListModel;
import sheep.view.ProjectNewPanel.UserTaskListModel;
import sheep.view.graphics2d.AnimationUtil;
import sheep.view.utils.swingx.StackLayout;

/**
 *
 * @author  geek
 */
public class UserChooserTopPanel extends JXPanel {
  
  //private final BackgroundMenuTitle backgroundTitle;
  private JPanel mainPanel;
  ///////////////////////////////////////////////////////////////////////////
  // Panneau users
  private JPanel leftPanel;
  private JPanel usersButtonPanel;
  private JPanel usersContentPanel;
  private UsersChooser userChooser;
  private JXTable table, tableRight;
  private UserTableModel tableModel, tableModelRight;
  private JXCollapsiblePane collapser;
  // Popup
  private UserEditPanel userEditPanel; 
  ///////////////////////////////////////////////////////////////////////////
  // Panneau Groupes
  private JPanel rightPanel;
  
  private Component[] repaintComponent;

  public PanelMode getPanelMode() {
    return panelMode;
  }

  public void setPanelMode(PanelMode panelMode) {
    this.panelMode = panelMode;
  }
  
  public static enum PanelMode { PROJECT, MANAGER, TASK};
  private PanelMode panelMode = PanelMode.PROJECT;
  
  /** Creates new form AgendaNotePanel */
  public UserChooserTopPanel(Workspace workSpace) {
    this.workSpace = workSpace;
    initComponents();
    

  }
  
  public void setTableHeaders(Object[] headers) {
    for(int i=0; i<headers.length; i++)
      table.getColumnModel().getColumn(i).setHeaderValue(headers[i]);
  }
  
  
  public void repaintTable(){
    if (panelMode== PanelMode.PROJECT){
      tableModelRight.setData(workSpace.getCurrentProject().getWorkersList());
    }else if (panelMode== PanelMode.MANAGER){
      tableModelRight.setData(workSpace.getCurrentProject().getManagers());
    }else if (panelMode== PanelMode.TASK){
      tableModelRight.setData(workSpace.getCurrentTask().getWorkersList());
    } 
    
    tableRight.repaint();
  }
  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  // <editor-fold defaultstate="collapsed" desc="Generated Code">
  private void initComponents() {

    MainPanel = new JXPanel();
    centerPanel = new javax.swing.JPanel();  
   
    northPanel = new javax.swing.JPanel();
    
    javax.swing.JLabel mainTitleLabel = new javax.swing.JLabel();
    
    cornerQuitBttn = new javax.swing.JButton();
    southPanel = new javax.swing.JPanel();
    validBttn = new ActionButton();
    quitBttn = new ActionButton();

    setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 45, 10, 45));
    setOpaque(false);
    setLayout(new javax.swing.BoxLayout(this, javax.swing.BoxLayout.PAGE_AXIS));

    MainPanel.setBackground(new java.awt.Color(255, 255, 255));
    MainPanel.setMaximumSize(new java.awt.Dimension(2147483647, 300));
    MainPanel.setMinimumSize(new java.awt.Dimension(73, 200));
    MainPanel.setPreferredSize(new java.awt.Dimension(100, 200));
    MainPanel.setLayout(new java.awt.BorderLayout());

    
    centerPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 10, 1, 10));
    centerPanel.setOpaque(false);
    centerPanel.setLayout(new java.awt.BorderLayout());

    ///////////////////////////////
    //DESSIN PRINCIPALE
    /////////////////////////////////////////////////////////////
    
    
    
    
    
    mainPanel = new JPanel();
    mainPanel.setOpaque(false);
    BorderLayout mainPanelLayout = new BorderLayout();
    mainPanelLayout.setHgap(15);
    mainPanel.setLayout(mainPanelLayout);
    centerPanel.add(mainPanel,BorderLayout.CENTER);
    
    ////////////////////////////////////////////////////////////////////////

    ////////////////////////////////////////////////////////////////////////
    // Panel des utilisateurs
    ////////////////////////////////////////////////////////////////////////
    leftPanel = new JPanel();
    leftPanel.setOpaque(false);
    BorderLayout leftPanelLayout = new BorderLayout();
    leftPanelLayout.setVgap(0);
    leftPanel.setLayout(leftPanelLayout);
    
    ////////////////////////////////////////////////////////////////////////
    // Création de la zone d'affichage des utilisateurs (en haut)    
    usersContentPanel = new JPanel();
    usersContentPanel.setOpaque(false);
    BorderLayout usersContentPanelLayout = new BorderLayout();
    usersContentPanelLayout.setVgap(10);
    usersContentPanel.setLayout(usersContentPanelLayout);
    
    JLabel titleLeftLabel = new JLabel();
    titleLeftLabel.setOpaque(false);
    titleLeftLabel.setFont(new java.awt.Font("Tahoma", 1, 16));
    titleLeftLabel.setForeground(new java.awt.Color(255, 255, 255));
    titleLeftLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    titleLeftLabel.setText("Liste des collaborateurs :");    
    usersContentPanel.add(titleLeftLabel, BorderLayout.NORTH);
    
    
    TableCellRenderer render = new UserCellRenderer();
    Object headers[] = { "Numéro", "Prénom", "Nom", "Job" };  
    table = new JXTable();
    tableModel = new UserTableModel(headers, workSpace.getWorkersList());
    table.setModel(tableModel);
    this.setTableHeaders(tableModel.getHeaders());
    userChooser = new UsersChooser(workSpace.getWorkersList(), UsersChooser.Mode.POPUP_PANEL);
    userChooser.setChooserWidth(75);
    userChooser.setChooserHeight(90);
    table.setDefaultRenderer(Object.class, render);
    table.setColumnControlVisible(true);
    table.setRowHeight(40);
    table.packAll();
    table.setFocusable(false);
    table.setColumnSelectionAllowed(false);
    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    table.setEditable(false);
    table.addMouseListener(new MouseListener(){

      @Override
      public void mouseClicked(MouseEvent e) {
        if(e.getClickCount()==2 && e.getButton()==1) {
        }
      }

      public void mousePressed(MouseEvent e) {}
      public void mouseReleased(MouseEvent e) {}
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}

    });
    
    JScrollPane scrollPane = new JScrollPane();
    scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPane.setViewportView(table);
    scrollPane.setOpaque(false);
    scrollPane.getVerticalScrollBar().setUI(new SheepScrollbarUI());
    
     
    usersContentPanel.add(new RoundedPanel(scrollPane,5,5,5,5), BorderLayout.CENTER);
    
    
    collapser = new JXCollapsiblePane();
    collapser.setOpaque(false);
    collapser.setLayout(new BorderLayout());
    collapser.setCollapsed(true);
    
    //JPanel temp = new JPanel(new StackLayout());
    //temp.add(new ContentPanel(), StackLayout.TOP);
    //temp.add(userChooser, StackLayout.TOP);
    collapser.setContentPane(new ContentPanel());
    collapser.add(userChooser, BorderLayout.SOUTH);
    
    userChooser.setSpacing(0.435);
    userChooser.setAmount(workSpace.getWorkersList().size()/2);
    usersContentPanel.add(collapser, BorderLayout.SOUTH);
    
    ////////////////////////////////////////////////////////////////////////
    // Création de la zone de boutons (en bas)
    usersButtonPanel = new JPanel();  
    //usersButtonPanel.setPreferredSize(new Dimension (200, 30));
    usersButtonPanel.setOpaque(false);
    usersButtonPanel.setBorder(BorderFactory.createEmptyBorder());
    JButton addUserBttn = new ActionButton("Ajouter");
    addUserBttn.addActionListener(new ActionListener(){
      @Override
      public void actionPerformed(ActionEvent e) {
        
         if(table.getSelectedRow() < tableModel.getRowCount()) {
            Object tb = tableModel.getValueAt(table.getSelectedRow(), 0);
            Worker wk = workSpace.getWorker(tb);
            
            if (panelMode== PanelMode.PROJECT){
              workSpace.getCurrentProject().getWorkersList().add(wk);
               tableModelRight.setData(workSpace.getCurrentProject().getWorkersList());
            }else if (panelMode== PanelMode.MANAGER){
              workSpace.getCurrentProject().getManagers().add(wk);
               tableModelRight.setData(workSpace.getCurrentProject().getManagers());
            }else if (panelMode== PanelMode.TASK){
              System.out.println("Ajout utilisateur tache :"  + workSpace.getCurrentTask().getName());
              workSpace.getCurrentTask().getWorkersList().add(wk);
               tableModelRight.setData(workSpace.getCurrentTask().getWorkersList());
            }                             
            tableRight.setModel(tableModelRight);
            tableRight.repaint();
            if (repaintComponent!=null)
              for(int i = 0; i < repaintComponent.length; i++)  
              if( repaintComponent[i] instanceof JList){
                if (panelMode== PanelMode.PROJECT){
                  if (((JList)repaintComponent[i]).getName().equals("task")){
                    UserTaskListModel ParticipantUserListModel =new UserTaskListModel(workSpace);
                    ((JList)repaintComponent[i]).setModel(ParticipantUserListModel);
                  }else if(((JList)repaintComponent[i]).getName().equals("project")){
                    UserListModel ParticipantUserListModel =new UserListModel(workSpace);
                    ((JList)repaintComponent[i]).setModel(ParticipantUserListModel);                    
                  }
                }else if (panelMode== PanelMode.MANAGER){
                  ManagerListModel ParticipantUserListModel =new ManagerListModel(workSpace);
                  ((JList)repaintComponent[i]).setModel(ParticipantUserListModel);
                }else if (panelMode== PanelMode.TASK){
                  if (((JList)repaintComponent[i]).getName().equals("task")){
                    UserTaskListModel ParticipantUserListModel =new UserTaskListModel(workSpace);
                    ((JList)repaintComponent[i]).setModel(ParticipantUserListModel);
                  }else if(((JList)repaintComponent[i]).getName().equals("project")){
                    UserListModel ParticipantUserListModel =new UserListModel(workSpace);
                    ((JList)repaintComponent[i]).setModel(ParticipantUserListModel);                    
                  }
                }                
              }
            
            //((UserTaskListModel)table.getModel()).get;
          }
      }
    });
    usersButtonPanel.add(addUserBttn);
    
    
    JButton modifUserBttn = new ActionButton("Détails");
    modifUserBttn.addActionListener(new ActionListener(){
      @Override
      public void actionPerformed(ActionEvent e) {
        //userEditPanel.setVisible(!userEditPanel.isVisible());
      }
    });
    usersButtonPanel.add(modifUserBttn);
    
    
    JButton collapserBtttn = new ActionButton("Portrait");
    collapserBtttn.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent e) {
        collapser.setCollapsed(!collapser.isCollapsed());
      }
    });
    usersButtonPanel.add(collapserBtttn);
   
    leftPanel.add(usersContentPanel,BorderLayout.CENTER);
    leftPanel.add(usersButtonPanel,BorderLayout.SOUTH);
     
    
    mainPanel.add(new RoundedPanel(leftPanel), BorderLayout.CENTER);
    
    ////////////////////////////////////////////////////////////////////////
    // Panel des groupes
    ////////////////////////////////////////////////////////////////////////
    BorderLayout rightBorderLayout= new BorderLayout();
    rightBorderLayout.setVgap(10);
    rightPanel = new JPanel(rightBorderLayout);
    rightPanel.setOpaque(false);
    rightPanel.setPreferredSize(new Dimension (400, 500));
    
    
    JLabel titleRightLabel = new JLabel();
    titleRightLabel.setOpaque(false);
    titleRightLabel.setFont(new java.awt.Font("Tahoma", 1, 16));
    titleRightLabel.setForeground(new java.awt.Color(255, 255, 255));
    titleRightLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    titleRightLabel.setText("Participants sélectionnés :");    
    rightPanel.add(titleRightLabel, BorderLayout.NORTH);
    
    TableCellRenderer renderRight = new UserCellRenderer();
    Object headersRight[] = { "Numéro", "Prénom", "Nom", "Job" };  
    tableRight = new JXTable();
    tableModelRight = new UserTableModel(headersRight, null);
    //tableRight.setModel(tableModelRight);
    this.setTableHeaders(tableModelRight.getHeaders());
    tableRight.setDefaultRenderer(Object.class, renderRight);
    tableRight.setColumnControlVisible(true);
    tableRight.setRowHeight(40);
    tableRight.packAll();
    tableRight.setFocusable(false);
    tableRight.setColumnSelectionAllowed(false);
    tableRight.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    tableRight.setEditable(false);
    tableRight.addMouseListener(new MouseListener(){

      @Override
      public void mouseClicked(MouseEvent e) {
        if(e.getClickCount()==2 && e.getButton()==1) {
          //Object[] tb = rows[table.getSelectedRow()];
          //Worker wk = workspace.getWorkerFromTab(tb);
          //System.out.println("User selected: " + wk.getFirstName() + " " + wk.getLastName());
        }
          
          //userChooser.setSelected(table.getSelectedRow());
      }

      public void mousePressed(MouseEvent e) {}
      public void mouseReleased(MouseEvent e) {}
      public void mouseEntered(MouseEvent e) {}
      public void mouseExited(MouseEvent e) {}

    });
    
    JScrollPane scrollPaneRight = new JScrollPane();
    scrollPaneRight.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
    scrollPaneRight.setViewportView(tableRight);
    scrollPaneRight.setOpaque(false);
    scrollPaneRight.getVerticalScrollBar().setUI(new SheepScrollbarUI());
    
    rightPanel.add(new RoundedPanel(scrollPaneRight,5,5,5,5), BorderLayout.CENTER);
    
    GridLayout rightBotoomGridLayout = new GridLayout (1,2);
    rightBotoomGridLayout.setHgap(10);
    FlowLayout rightBottomFlowLayout = new FlowLayout();
    rightBottomFlowLayout.setAlignment(FlowLayout.CENTER);
    rightBottomFlowLayout.setHgap(10);
    
    JPanel rightBottomPanel = new JPanel(rightBottomFlowLayout);
    rightBottomPanel.setPreferredSize(new Dimension (200, 30));
    rightBottomPanel.setOpaque(false);
    rightBottomPanel.add(new ActionButton("Détails"));
    rightBottomPanel.add(new ActionButton("Supprimer"));
    rightPanel.add(rightBottomPanel, BorderLayout.SOUTH);
    mainPanel.add(new RoundedPanel(rightPanel), BorderLayout.EAST);
    
        
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    MainPanel.add(centerPanel, java.awt.BorderLayout.CENTER);

    northPanel.setOpaque(false);
    northPanel.setLayout(new java.awt.BorderLayout());
    northPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 15, 10));
    mainTitleLabel.setFont(new java.awt.Font("Tahoma", 1, 20));
    mainTitleLabel.setForeground(new java.awt.Color(255, 255, 255));
    mainTitleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
    mainTitleLabel.setText("Selectionner les participants");
    northPanel.add(mainTitleLabel, java.awt.BorderLayout.CENTER);

    cornerQuitBttn.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/button-close.png"))); // NOI18N
    cornerQuitBttn.setToolTipText("Close editor");
    cornerQuitBttn.setBorder(null);
    cornerQuitBttn.setBorderPainted(false);
    cornerQuitBttn.setContentAreaFilled(false);
    cornerQuitBttn.setFocusPainted(false);
    cornerQuitBttn.setFocusable(false);
    cornerQuitBttn.setMargin(new java.awt.Insets(0, 0, 0, 0));
    cornerQuitBttn.setPressedIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/button-close-pressed.png"))); // NOI18N
    cornerQuitBttn.setRolloverIcon(new javax.swing.ImageIcon(getClass().getResource("/resources/images/button-close-over.png"))); // NOI18N
    cornerQuitBttn.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        cornerQuitBttnActionPerformed(evt);
      }
    });
    northPanel.add(cornerQuitBttn, java.awt.BorderLayout.EAST);

    MainPanel.add(northPanel, java.awt.BorderLayout.PAGE_START);

    //southPanel.setBorder(javax.swing.BorderFactory.createEmptyBorder(0, 1, 0, 1));
    southPanel.setOpaque(false);
    southPanel.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT, 15, 5));

    validBttn.setText("   Ok    ");
    southPanel.add(validBttn);
    validBttn.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        OKBttnActionPerformed(evt);
      }
    });
    
    quitBttn.setText("Annuler");
    quitBttn.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        quitBttnActionPerformed(evt);
      }
    });
    southPanel.add(quitBttn);

    MainPanel.add(southPanel, java.awt.BorderLayout.PAGE_END);
    MainPanel.setOpaque(true);
    MainPanel.setBackgroundPainter(new sheep.view.utils.swingx.PainterBlackCustom());
    add(new RoundedPanel(MainPanel));
  }// </editor-fold>

  private void cornerQuitBttnActionPerformed(java.awt.event.ActionEvent evt) {
    final Container parent = this.getParent();
    Animator fadeOut = AnimationUtil.createFadeOutAnimation(this);
    fadeOut.addTarget(new TimingTarget() {
      @Override
      public void begin() {}
      @Override
      public void end() {
        setVisible2(false);
        parent.repaint();
      }
      @Override
      public void timingEvent(float f) {}
      @Override
      public void repeat() {}
    });
    fadeOut.start();
}

  private void quitBttnActionPerformed(java.awt.event.ActionEvent evt) {
        final Container parent = this.getParent();
    Animator fadeOut = AnimationUtil.createFadeOutAnimation(this);
    fadeOut.addTarget(new TimingTarget() {
      @Override
      public void begin() {}
      @Override
      public void end() {
        setVisible2(false);
        parent.repaint();
      }
      @Override
      public void timingEvent(float f) {}
      @Override
      public void repeat() {}
    });
    fadeOut.start();
  }
 
    private void OKBttnActionPerformed(java.awt.event.ActionEvent evt) {
        final Container parent = this.getParent();
    Animator fadeOut = AnimationUtil.createFadeOutAnimation(this);
    fadeOut.addTarget(new TimingTarget() {
      @Override
      public void begin() {
      ////////////////////////////////////
      // RECUPERATION DES VALEURS
      ///////////////////////////////////////
      }
      @Override
      public void end() {
        setVisible2(false);
        parent.repaint();
      }
      @Override
      public void timingEvent(float f) {}
      @Override
      public void repeat() {}
    });
    fadeOut.start();
  }
    
    void setVisible2 (boolean aFlag){
    super.setVisible(aFlag);
    setEnabled(aFlag);
    setFocusable(aFlag);
    if (aFlag){
      ///////////////////////////
      //INIT
      ///////////////////////////
      
   if (panelMode== PanelMode.PROJECT){
      userChooser.setWokersList(workSpace.getCurrentProject().getWorkersList());
      userChooser.setAmount(workSpace.getCurrentProject().getWorkersList().size());
      userChooser.findAvatars();
      userChooser.refresh();
      userChooser.repaint();
    }else if (panelMode== PanelMode.MANAGER){
      userChooser.setWokersList(workSpace.getCurrentProject().getManagers());
      userChooser.setAmount(workSpace.getCurrentProject().getManagers().size());
      userChooser.findAvatars();
      userChooser.refresh();
      userChooser.repaint();
    }else if (panelMode== PanelMode.TASK){
      userChooser.setWokersList(workSpace.getCurrentTask().getManagers());
      userChooser.setAmount(workSpace.getCurrentTask().getManagers().size());
      userChooser.findAvatars();
      userChooser.refresh();
      userChooser.repaint();
    } 
          
          
          

    }
  }


  @Override
  public void setVisible(final boolean aFlag) {
    final Container parent = this.getParent();   
    if (!aFlag){ 
      Animator fadeOut = AnimationUtil.createFadeOutAnimation(this);
      fadeOut.addTarget(new TimingTarget() {
        @Override
        public void begin() {}
        @Override
        public void end() {
            setVisible2(false);
            parent.repaint();            
        }
        @Override
        public void timingEvent(float f) {}
        @Override
        public void repeat() {}
      });
      fadeOut.start();
    }else{
        Animator fadeIn = AnimationUtil.createFadeInAnimation(this);
        fadeIn.addTarget(new TimingTarget() {
        @Override
        public void begin() {setVisible2(true);}
        @Override
        public void end() {
          parent.repaint();
        }
        @Override
        public void timingEvent(float f) {}
        @Override
        public void repeat() {}
      });
      fadeIn.start();   
    }
  }
  
  
  // Variables declaration - do not modify
  private JXPanel MainPanel;
  private javax.swing.JPanel centerPanel;
  private javax.swing.JButton cornerQuitBttn;

  private javax.swing.JPanel northPanel;
  private javax.swing.JButton quitBttn;
  private javax.swing.JPanel southPanel;

  private javax.swing.JButton validBttn;
  
  private Workspace workSpace;

  public Component[] getRepaintComponent() {
    return repaintComponent;
  }

  public void setRepaintComponent(Component[] repaintComponent) {
    this.repaintComponent = repaintComponent;
  }

  // End of variables declaration
}



